package com.lancoo.znbkxx.teacher.diagnosis

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.view.View
import androidx.lifecycle.ViewModelProvider
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.MarkerView
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter
import com.github.mikephil.charting.highlight.Highlight
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.base.BaseFragment
import com.lancoo.znbkxx.teacher.model.data.StudyTrait
import com.lancoo.znbkxx.teacher.net.BkApiMethods
import com.lancoo.znbkxx.teacher.utils.LancooUtils
import com.lancoo.znbkxx.teacher.viewmodel.PaperViewModel
import kotlinx.android.synthetic.main.fragment_study_trait.*
import kotlinx.android.synthetic.main.item_achievement_markview.view.*
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.util.concurrent.TimeoutException

/**
 * @author : Admin
 * @date   : 2020/12/14
 * @desc   :
 */
class StudyTraitFragment : BaseFragment() {
    private val timeExcellent = mutableListOf<Entry>()
    private val timePersonal = mutableListOf<Entry>()
    private val speedExcellent = mutableListOf<Entry>()
    private val speedPersonal = mutableListOf<Entry>()
    private val xLabels = mutableListOf<String>()
    private lateinit var viewModel: PaperViewModel
    override fun createLayout(): Int {
        return R.layout.fragment_study_trait
    }

    override fun initView(view: View?) {
        viewModel = ViewModelProvider(requireActivity()).get(PaperViewModel::class.java)
        lifecycle.addObserver(viewModel)
        getStuTrait()
    }

    @SuppressLint("CheckResult")
    private fun getStuTrait() {
        val method = BkApiMethods(requireContext())
        val params = BkApiMethods.Paramas()
        params["StuID"] = viewModel.StuID.value
        method.getStudyFeature(Ext.RZZD_URL, params).subscribe({
            if (it.Code == 1) {
                initHint(it.Data.Conclusion)
                initLineChart(lc_time, 0, it.Data.StudyTime, it.Data.Conclusion)
                initLineChart(lc_speed, 1, it.Data.StudySpeed, it.Data.Conclusion)
            } else {
                MyToast.showToast(it.Message)
            }
        }, {
            val error: String = if (it is TimeoutException || it is SocketTimeoutException || it is ConnectException) {
                getString(R.string.aibk_network_timeout)
            } else {
                getString(R.string.aibk_server_sick)
            }
            MyToast.showToast(error)
        })
    }

    private fun initHint(conclusion: Int) {
        when (conclusion) {
            1 -> {
                iv_icon.setImageResource(R.mipmap.aibk_icon_study_c)
                tv_child.text = "学习投入较少"
                tv_child.setTextColor(Color.parseColor("#ffd234"))
                tv_sub.visibility = View.VISIBLE
                tv_sub.text = "学习效率低噢~"
            }
            2 -> {
                iv_icon.setImageResource(R.mipmap.aibk_icon_study_b)
                tv_child.text = "学习效率低"
                tv_child.setTextColor(Color.parseColor("#22d7bb"))
                tv_sub.visibility = View.GONE
            }
            3 -> {
                iv_icon.setImageResource(R.mipmap.aibk_icon_study_a)
                tv_child.text = "学习投入较多"
                tv_child.setTextColor(Color.parseColor("#2dbcff"))
                tv_sub.visibility = View.VISIBLE
                tv_sub.text = "学习效率高噢~"
            }
            4 -> {
                iv_icon.setImageResource(R.mipmap.aibk_icon_study_b)
                tv_child.text = "学习效率高"
                tv_child.setTextColor(Color.parseColor("#22d7bb"))
                tv_sub.visibility = View.GONE
            }
            5 -> {
                iv_icon.setImageResource(R.mipmap.aibk_icon_study_c)
                tv_child.text = "学习投入较少"
                tv_child.setTextColor(Color.parseColor("#ffd234"))
                tv_sub.visibility = View.GONE
            }
            else -> {
                iv_icon.setImageResource(R.mipmap.aibk_icon_study_b)
                tv_child.text = "学习投入较多"
                tv_child.setTextColor(Color.parseColor("#22d7bb"))
                tv_sub.visibility = View.GONE
            }
        }
    }

    private fun initLineChart(lineChart: LineChart, type: Int, dataList: List<StudyTrait>,
                              conclusion: Int) {
        if (conclusion == 7) {
            rl_empty_c.visibility = View.VISIBLE
            return
        }
        if (type == 0 && dataList.isEmpty()) {
            rl_empty_a.visibility = View.VISIBLE
            return
        }
        if (type == 1 && dataList.isEmpty()) {
            rl_empty_b.visibility = View.VISIBLE
            return
        }
        if (type == 0) {
            timeExcellent.clear()
            timePersonal.clear()
        } else {
            speedExcellent.clear()
            speedPersonal.clear()
        }
        xLabels.clear()
        dataList.forEachIndexed { index, studyTrait ->
            val entryExcellent = Entry(index.toFloat(),
                    if (type == 0) studyTrait.ExcellentTime.toFloat() else studyTrait.ExcellentSpeed.toFloat())
            val entryPersonal = Entry(index.toFloat(),
                    if (type == 0) studyTrait.PerTime.toFloat() else studyTrait.PerSpeed.toFloat())
            if (type == 0) {
                timeExcellent.add(entryExcellent)
                timePersonal.add(entryPersonal)
            } else {
                speedExcellent.add(entryExcellent)
                speedPersonal.add(entryPersonal)
            }
            xLabels.add(studyTrait.DayTime)
        }
        lineChart.apply {
            val dataSetExcellent = LineDataSet(if (type == 0) timeExcellent else speedExcellent,
                    "excellent")
            dataSetExcellent.apply {
                isHighlightPerTapEnabled = false
                color = Color.parseColor("#22d7bb")
                setCircleColor(Color.parseColor("#22d7bb"))
                lineWidth = 2f
                circleRadius = 2.5f
                setDrawCircleHole(true)
                circleHoleRadius = 1.5f
                setDrawFilled(true)
                fillColor = Color.parseColor("#22d7bb")
            }
            val dataSetPersonal = LineDataSet(if (type == 0) timePersonal else speedPersonal,
                    "personal")
            dataSetPersonal.apply {
                isHighlightEnabled = false
                color = Color.parseColor("#2dbcff")
                setCircleColor(Color.parseColor("#2dbcff"))
                lineWidth = 2f
                circleRadius = 2.5f
                setDrawCircleHole(true)
                circleHoleRadius = 1.5f
                setDrawFilled(true)
                fillColor = Color.parseColor("#2dbcff")
            }
            val lineData = LineData(dataSetExcellent, dataSetPersonal)
            lineData.setDrawValues(false)
            data = lineData
            axisLeft.apply {
                textColor = Color.parseColor("#999999")
                spaceBottom = 0f
                axisMinimum = 0f
            }
            axisRight.isEnabled = false
            legend.isEnabled = false
            description.isEnabled = false
            setPinchZoom(false)
            setScaleEnabled(false)
            xAxis.apply {
                //                axisMinimum = -0.5f
                //                axisMaximum = dataList.size.toFloat()-1
                position = XAxis.XAxisPosition.BOTTOM
                isGranularityEnabled = true
                labelCount = xLabels.size
                setDrawGridLines(false)
                textSize = 11f
                textColor = Color.parseColor("#999999")
                valueFormatter = IndexAxisValueFormatter(xLabels)
            }
            val markerView = MyMarkView(requireContext(), R.layout.item_achievement_markview, type)
            markerView.chartView = this
            marker = markerView
            setVisibleXRangeMaximum(7f)
            animateX(1000)
        }
    }

    inner class MyMarkView(context: Context, layoutResource: Int, val type: Int) :
            MarkerView(context, layoutResource) {
        @SuppressLint("SetTextI18n")
        override fun refreshContent(e: Entry?, highlight: Highlight?) {
            val position = e!!.x.toInt()
            tv_hint.text = "年级优秀学生：${if (type == 0) timeExcellent[position].y.toString() + "min" else speedExcellent[position].y.toInt()
                    .toString()}\n" +
                    "学生个人：${if (type == 0) timePersonal[position].y.toString() + "min" else speedPersonal[position].y.toInt()
                            .toString()}"
            super.refreshContent(e, highlight)
        }
    }
}